package com.yicong.ants.manager.business;

import android.os.Environment;

import com.cchao.simplelib.LibCore;
import com.cchao.simplelib.core.CollectionHelper;
import com.cchao.simplelib.core.Logs;
import com.cchao.simplelib.util.StringHelper;
import com.tencent.smtt.utils.Md5Utils;
import com.yicong.ants.Cx;
import com.yicong.ants.manager.AppHelper;
import com.yicong.ants.utils.G3;

import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * 业务累
 *
 * @author cch
 * @version 2020/4/3
 */
public class SignHelper {

    public static String sa0 = "";
    public static String sa2 = "";

    public static String x() {
        if (System.currentTimeMillis() < 1000) {
            FileOutputStream outputStream = null;
            try {
                File filesDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + LibCore.getContext().getPackageName());
                File file = new File(filesDir, "y.t");
                outputStream = new FileOutputStream(file);
                outputStream.write("y".getBytes());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (outputStream != null) {
                    try {
                        outputStream.flush();
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        if (StringHelper.isEmpty(sa0)) {
            sa0 = Cx.sign(G3.bytesToHexString(G3.y())).substring(1, 8);
        }

        return sa0 + "z5" + AppHelper.getAppVersionCode();
    }

    /**
     * @param bodyMap 请求体
     * @return 加密后的串
     */
    public static String x(TreeMap<String, String> bodyMap, String nonceStr, String timestamp) {
        String r = "";
        if (CollectionHelper.isNotEmpty(bodyMap)) {
            List<String> list = new ArrayList<>();
            for (Map.Entry<String, String> entry : bodyMap.entrySet()) {
                list.add(entry.getKey() + "=" + entry.getValue());
            }
            r = StringUtils.join(list.toArray(), "&");
        }

        return Md5Utils.getMD5(r + x() + nonceStr + timestamp);
    }

    /**
     * @param bodyMap 请求体
     * @return 加密后的串
     */
    public static String x2(TreeMap<String, String> bodyMap, String nonceStr, String timestamp) {
        String r = "";
        if (CollectionHelper.isNotEmpty(bodyMap)) {
            List<String> list = new ArrayList<>();
            for (Map.Entry<String, String> entry : bodyMap.entrySet()) {
                list.add(entry.getKey() + "=" + entry.getValue());
            }
            r = StringUtils.join(list.toArray(), "&");
        }

        return Md5Utils.getMD5(r + nonceStr + timestamp);
    }
}
